package com.zm.services.impl;

import com.zm.dao.IAccountDao;
import com.zm.domain.account;
import com.zm.services.IAcountServices;
import com.zm.utils.TransactionManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;

@Component("AccountServicesImpl")
public class AccountServicesImpl  implements IAcountServices {
    @Resource(name = "accountDao")
    private IAccountDao accountDao;

    private TransactionManager transactionManager;


    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void findAllAccount() {
        List<account> accoList=accountDao.findAllAccount();
        for (account ac:accoList
             ) {
            System.out.println(ac);
        }
    }

    public void saveAccount(account acc) {
        System.out.println("已经保存完毕!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        accountDao.saveAccount(acc);
    }

    public void tranMoney(Integer sourceId, Integer targetId, Integer tranMoney) {
        try{
            //开启事务
            transactionManager.beginTransation();
            //获取源账户
            account sourceAccout=accountDao.findAllcountById(sourceId).get(0);
            //获取目标账户
            account targetAccount=accountDao.findAllcountById(targetId).get(0);
            //源账户扣钱
            sourceAccout.setMoney(sourceAccout.getMoney()-tranMoney);
            //目标账户加钱
            targetAccount.setMoney(targetAccount.getMoney()+tranMoney);
            //将修改过的数据更新至数据库
            accountDao.updateAccount(sourceAccout);

            //int i=1/0;
            accountDao.updateAccount(targetAccount);
            //提交事务
            transactionManager.commit();
        }catch (Exception e){
            //如果出现异常回滚事务
            System.out.println("yichang !!!!!");
            transactionManager.rollback();
        }finally {
            //关闭当前线程的事务连接并且将连接与线程断开
            transactionManager.removeConn();
        }

    }


    @PostConstruct
    public void initMethod(){
        System.out.println("对象被初始化");
    }
    @PreDestroy
    public void destoryMethod(){
        System.out.println("对象被销毁了");
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
}
